from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app import db
from app.models.project import Project, ProjectObjectiveLink
from app.models.status import ProgressUpdate
from datetime import datetime

bp = Blueprint('projects', __name__, url_prefix='/api/projects')

@bp.route('', methods=['GET'])
@login_required
def get_projects():
    """获取项目列表"""
    owner_id = request.args.get('owner_id', type=int)
    status = request.args.get('status')
    include_objectives = request.args.get('include_objectives', 'false').lower() == 'true'

    query = Project.query

    # 权限过滤
    if not current_user.is_manager():
        query = query.filter_by(owner_id=current_user.id)
    elif owner_id:
        query = query.filter_by(owner_id=owner_id)

    if status:
        query = query.filter_by(status=status)

    projects = query.order_by(Project.created_at.desc()).all()
    return jsonify([proj.to_dict(include_objectives=include_objectives) for proj in projects]), 200

@bp.route('/<int:id>', methods=['GET'])
@login_required
def get_project(id):
    """获取单个项目详情"""
    project = Project.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and project.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    return jsonify(project.to_dict(include_objectives=True)), 200

@bp.route('', methods=['POST'])
@login_required
def create_project():
    """创建项目"""
    data = request.get_json()

    required_fields = ['name', 'start_date']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    project = Project(
        name=data['name'],
        description=data.get('description'),
        owner_id=data.get('owner_id', current_user.id),
        start_date=datetime.strptime(data['start_date'], '%Y-%m-%d').date(),
        end_date=datetime.strptime(data['end_date'], '%Y-%m-%d').date() if data.get('end_date') else None
    )

    db.session.add(project)
    db.session.commit()

    return jsonify(project.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
@login_required
def update_project(id):
    """更新项目"""
    project = Project.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and project.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    data = request.get_json()

    # 记录进度变化
    if 'progress' in data and data['progress'] != project.progress:
        progress_update = ProgressUpdate(
            project_id=project.id,
            previous_value=project.progress,
            new_value=data['progress'],
            notes=data.get('notes'),
            updated_by=current_user.id
        )
        db.session.add(progress_update)

    updatable_fields = ['name', 'description', 'progress', 'status', 'owner_id']
    for field in updatable_fields:
        if field in data:
            setattr(project, field, data[field])

    if 'start_date' in data:
        project.start_date = datetime.strptime(data['start_date'], '%Y-%m-%d').date()
    if 'end_date' in data:
        project.end_date = datetime.strptime(data['end_date'], '%Y-%m-%d').date()

    db.session.commit()
    return jsonify(project.to_dict()), 200

@bp.route('/<int:id>', methods=['DELETE'])
@login_required
def delete_project(id):
    """删除项目"""
    project = Project.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and project.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    db.session.delete(project)
    db.session.commit()
    return jsonify({'message': 'Project deleted successfully'}), 200

@bp.route('/link', methods=['POST'])
@login_required
def link_to_objective():
    """关联项目到目标"""
    data = request.get_json()

    required_fields = ['project_id', 'objective_id']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    project = Project.query.get_or_404(data['project_id'])

    # 权限检查
    if not current_user.is_manager() and project.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    # 检查是否已关联
    existing_link = ProjectObjectiveLink.query.filter_by(
        project_id=data['project_id'],
        objective_id=data['objective_id']
    ).first()

    if existing_link:
        return jsonify({'error': 'Link already exists'}), 409

    link = ProjectObjectiveLink(
        project_id=data['project_id'],
        objective_id=data['objective_id'],
        contribution_weight=data.get('contribution_weight', 1.0)
    )

    db.session.add(link)
    db.session.commit()

    return jsonify(link.to_dict()), 201

@bp.route('/link/<int:id>', methods=['DELETE'])
@login_required
def unlink_from_objective(id):
    """取消项目与目标的关联"""
    link = ProjectObjectiveLink.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and link.project.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    db.session.delete(link)
    db.session.commit()

    return jsonify({'message': 'Link removed successfully'}), 200